import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'app_img.dart';

/// 图片预览器
class PhotoViewer extends StatefulWidget {
  const PhotoViewer({
    Key? key,
    required this.images,
    this.initIndex = 0,
    this.heroTag,
  }) : super(key: key);

  @override
  _PhotoViewerState createState() => _PhotoViewerState();

  final List<String> images;
  final int initIndex;

  final String? heroTag;
}

class _PhotoViewerState extends State<PhotoViewer> with SafeState<PhotoViewer> {
  late ExtendedPageController _controller;
  late int _currentIndex = widget.initIndex + 1;

  @override
  void initState() {
    super.initState();
    _controller = ExtendedPageController(initialPage: widget.initIndex);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => pop(context),
      child: SafeScaffold(
        backgroundColor: Colors.transparent,
        titleText: '$_currentIndex/${widget.images.length}',
        body: ExtendedImageGesturePageView.builder(
          itemBuilder: (BuildContext context, int index) {
            return _ImageItem(
              url: widget.images[index],
              index: index,
              heroTag: widget.heroTag,
            );
          },
          controller: _controller,
          canScrollPage: (GestureDetails? g) => true,
          itemCount: widget.images.length,
          scrollDirection: Axis.horizontal,
          onPageChanged: (int index) => safeSetState(() => _currentIndex = index + 1),
        ),
      ),
    );
  }
}

/// 图片项
class _ImageItem extends StatelessWidget {
  const _ImageItem({
    Key? key,
    required this.url,
    required this.index,
    this.heroTag,
  }) : super(key: key);

  final String url;

  final int index;

  final String? heroTag;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ExtendedImageSlidePage(
        slideAxis: SlideAxis.vertical,
        slideType: SlideType.wholePage,
        resetPageDuration: const Duration(milliseconds: 300),
        child: Container(
          height: double.infinity,
          alignment: Alignment.center,
          child: AppImg(
            url: url,
            mode: ExtendedImageMode.gesture,
            enableSlideOutPage: true,
            heroBuilderForSlidingPage: (Widget r) {
              if (heroTag != null) return Hero(tag: heroTag! + index.toString(), child: r);

              return r;
            },
          ),
        ),
      ),
    );
  }
}
